package com.gitee.qdbp.base.shiro.session;

import java.io.Serializable;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
import com.gitee.qdbp.able.beans.Duration;
import com.gitee.qdbp.able.beans.Duration.Millis;
import com.gitee.qdbp.base.shiro.cache.VolatileCache;

/**
 * 可设置过期时间的SessionDao
 *
 * @author zhaohuihua
 * @version 180419
 */
public class VolatileSessionDao extends EnterpriseCacheSessionDAO implements SessionTimeoutAware {

    /** Session过期时间 **/
    private long sessionTimeout;
    /** 可处理过期时间的CachingRealm **/
    private VolatileCachingManager volatileCachingManager;

    protected void cache(Session session, Serializable sessionId, Cache<Serializable, Session> cache) {
        super.cache(session, sessionId, cache);

        Duration duration = new Millis(sessionTimeout);

        // 设置SESSION的过期时间
        if (session != null && sessionTimeout > 0 && cache instanceof VolatileCache) {
            @SuppressWarnings("unchecked")
            VolatileCache<Serializable> vcache = (VolatileCache<Serializable>) cache;
            vcache.expire(sessionId, duration);
        }

        // 设置认证信息和授权信息的过期时间
        if (session != null && sessionTimeout > 0 && volatileCachingManager != null) {
            volatileCachingManager.expire(session, duration);
        }
    }

    /** Session过期时间 **/
    public long getSessionTimeout() {
        return sessionTimeout;
    }

    /** Session过期时间 **/
    public void setSessionTimeout(long sessionTimeout) {
        this.sessionTimeout = sessionTimeout;
    }

    /** 可处理过期时间的CachingManager **/
    public VolatileCachingManager getVolatileCachingManager() {
        return volatileCachingManager;
    }

    /** 可处理过期时间的CachingRealm **/
    public void setVolatileCachingManager(VolatileCachingManager volatileCachingManager) {
        this.volatileCachingManager = volatileCachingManager;
    }

}
